package org.ehe.erp.listener;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ehe.business.monitor.MonitorMethod;
import org.ehe.business.overdue.extract.QualityDataExtractor;
import org.ehe.common.satoken.utils.LoginHelper;
import org.ehe.common.sse.dto.SseMessageDto;
import org.ehe.common.sse.utils.SseMessageUtils;
import org.ehe.erp.domain.quality.ErpQualityTask;
import org.ehe.erp.event.BomArrivalCompleteEvent;
import org.ehe.erp.service.quality.ErpQualityTaskService;
import org.ehe.system.service.ISysUserService;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 产品到货事件监听器
 * 用于监听BOM物料到货完成事件，自动创建质检任务
 *
 * @author zhangnn
 * @className ProductArrivalEventListener
 * @description 监听到货事件，触发质检任务创建
 * @date 2025-09-11 15:30:00
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ProductArrivalEventListener {

    private final ErpQualityTaskService qualityTaskService;
    private final ScheduledExecutorService scheduledExecutorService;
    private final ISysUserService userService;

    /**
     * 监听BOM采购到货完成事件
     * 当某BOM下的所有批次物料都到货后，自动创建质检任务
     */
    @Async
    @EventListener
    @MonitorMethod(bizType = "qualityOverdue", extractor = QualityDataExtractor.class)
    public Future<ErpQualityTask> handleBomArrivalCompleteEvent(BomArrivalCompleteEvent event) {
        log.info("接收到BOM到货完成事件，BOM ID：{}", event.getBomId());
        try {
            // 自动创建质检任务
            ErpQualityTask task = qualityTaskService.autoCreateQualityTaskByBomArrival(
                event.getBomId(), event.getBomName(),event.getOrderNo());

//            if (Objects.nonNull(task)) {
//                Long userId = userService.selectUserByUserName("admin").getUserId();
//                scheduledExecutorService.schedule(() -> {
//                    SseMessageDto dto = new SseMessageDto();
//                    dto.setMessage("新的【" + event.getOrderNo() + "】订单质检任务已生成，请及时处理！");
//                    dto.setUserIds(List.of(userId));
//                    SseMessageUtils.publishMessage(dto);
//                }, 2, TimeUnit.SECONDS);
//
//                log.info("BOM {} 质检任务创建成功，订单编号{}", event.getBomId(), event.getOrderNo());
//            } else {
//                log.warn("BOM {} 质检任务创建失败或已存在", event.getBomId());
//            }
            return new AsyncResult<>(task);
        } catch (Exception e) {
            log.error("处理BOM到货完成事件失败，BOM ID：{}", event.getBomId(), e);
            return new AsyncResult<>(null);
        }
    }
}
